<%@ page contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp"%>
<%@page import="dbexp.model.Table"%>
<%@page import="dbexp.model.Column"%>
<%@page import="dbexp.model.db.DbUser"%>
<%@page import="dbexp.connection.DbMetaData"%>
<%@page import="dbexp.connection.DbConnection"%>
<%@page import="org.json.JSONObject"%>
<%@page import="org.json.JSONArray"%>
<%@page import="org.json.JSONException"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%
DbUser u = (DbUser)session.getAttribute("USER");
String name = request.getParameter("name");
String schema = request.getParameter("schema");
String tablespace = request.getParameter("tablespace");
String colsData = request.getParameter("data");
boolean brak = (name==null || name.trim().equals("null")) && (schema==null || schema.trim().equals("null"));
Table t = new Table(name,schema);
Table oldTable = null;
t.setTableSpace(tablespace);
if(!brak){
	List<Column> oldColumns = null;
	int ACTION = DbConnection.NONE;
	if( (oldTable = DbMetaData.getTable(u,name,schema)).requiredFieldIsNotNull() ){
		ACTION = DbConnection.ALTER_COLUMN;
		oldColumns = oldTable.getColumns();
	}
	JSONArray data = null;
	try{
	data = new JSONArray(colsData);
	}catch (JSONException e) {
		try {
			data = new JSONArray("["+colsData+"]");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}
	for (int i = 0; i < data.length(); i++) {
		try {
			JSONObject obj = data.getJSONObject(i);
			Column col = new Column(obj.getString("name"),schema,name);
			col.setDataType(obj.getString("dataType"));
			col.setDataSize(obj.getLong("size"));
			col.setDataScale(obj.getString("scale"));
			col.setNullable(obj.getBoolean("nullable"));
			col.setDataDefault(obj.getString("default"));
			if(oldColumns!=null){
				if(oldColumns.contains(col)){
					col.setAction(DbConnection.ALTER);
				}else{
					col.setAction(DbConnection.NONE);
				}
			}
			t.addColumn(col);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		DbMetaData.operateObject(u,t,ACTION);
	}
	
	t = DbMetaData.getTable(u, name.toUpperCase(), schema.toUpperCase());
	List<Column> columns = t.getColumns();
	JSONArray array = new JSONArray();
	for(int i=0;i<columns.size();i++){
		Column c = columns.get(i);
		array.put(i, new JSONObject().put("id",i).put("name",c.getName()).put("dataType",c.getDataType()).put("size",c.getSize()).put("scale",c.getScale()).put("nullable",c.isNullable()).put("default",c.getDefault()) );
	}
	
	JSONObject my_out = new JSONObject().put("success", true).put("data",array);
	
	out.clearBuffer();%><%=my_out %>
<%}else{%>
<%=new JSONObject().put("success", false) %>
<%}%>